package com.stylefeng.guns.modular.capitalBudget.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.capitalBudget.MapToCapitalBudget;
import com.stylefeng.guns.modular.capitalBudget.model.CapitalBudgetImportHandler;
import com.stylefeng.guns.modular.payroll.MapToPayroll;
import com.stylefeng.guns.modular.rate.service.IRateService;
import com.stylefeng.guns.modular.system.model.CapitalBudget;
import com.stylefeng.guns.modular.system.dao.CapitalBudgetMapper;
import com.stylefeng.guns.modular.capitalBudget.service.ICapitalBudgetService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.system.model.Payroll;
import com.stylefeng.guns.modular.system.model.Rate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-07-16
 */
@Service
public class CapitalBudgetServiceImpl extends ServiceImpl<CapitalBudgetMapper, CapitalBudget> implements ICapitalBudgetService {

    @Autowired
    private IRateService rateService;

    /**
     * 下载
     * @param list
     * @param revDate
     * @param platform
     * @return
     */
    @Override
    public Map<String, Object> load(List<CapitalBudget> list,String revDate,String platform,String platformName) {
        //获取费率
        Rate rate = rateService.search(revDate);
        Map<String, Object> resultmMap = new HashMap<String, Object>();//返回下载数据
        List<Map<String, Object>> loadMapList = new ArrayList<Map<String, Object>>();//下载数据集合
        Double incomeTtatol=0.0;
        Double eTatol = 0.0;
        for (CapitalBudget capitalBudget:list) {
            Map<String, Object> loadMap = new HashMap<String, Object>();//下载数据
            if (capitalBudget.getNumber()!=null){
                if (capitalBudget.getNumber()==1) {
                    incomeTtatol += capitalBudget.getIncomeRMB();
                    loadMap.put("number", "一");
                }else if (capitalBudget.getNumber()==2){
                    loadMap.put("number","二");
                    eTatol += capitalBudget.getExpenditureRMB();
                }else if (capitalBudget.getNumber()==3){
                    loadMap.put("number","三");
                    eTatol += capitalBudget.getExpenditureRMB();
                }
            }else {
                loadMap.put("number",null);
            }
            loadMap.put("project",capitalBudget.getProject());
            loadMap.put("username", capitalBudget.getProject() );
            loadMap.put("incomePS",capitalBudget.getIncomePS());
            loadMap.put("incomeRMB",capitalBudget.getIncomeRMB());
            loadMap.put("expenditurePS",capitalBudget.getExpenditurePS());
            loadMap.put("expenditureRMB",capitalBudget.getExpenditureRMB());


            loadMapList.add(loadMap);
        }
        resultmMap.put("maplist", loadMapList);
        resultmMap.put("name",platformName+"资金预算表");
        resultmMap.put("time",revDate);
        resultmMap.put("platform",platform.toUpperCase());
        resultmMap.put("rate",rate.getRate());
        resultmMap.put("incometatol",incomeTtatol);
        resultmMap.put("total",eTatol);
        resultmMap.put("missing",incomeTtatol-eTatol);
        return resultmMap;
    }

    /**
     * 上传
     * @param file
     */
    @Override
    public void adds(MultipartFile file) throws GunsException,Exception {

        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(2);//标题所占行数
            params.setHeadRows(2);//表头所占行数
            params.setDataHandler(new CapitalBudgetImportHandler());
            //解析表格数据
            List<Map<String, Object>> list = ExcelImportUtil.importExcel(
                    file.getInputStream(), Map.class, params);


            //获取标题中的工资日期
            String fileName = file.getOriginalFilename();
            //获取文件标题中的报表统计时间
            String payTime = fileName.substring(fileName.length() - 17, fileName.length() - 10);

            //检查是否存在当月数据,如果存在则删除原有的重新上传
            String platform = ShiroKit.getUser().getDeptcode();
            if (!fileName.toUpperCase().contains(platform.toUpperCase())) {
                throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "请检查要上传的资金预算表是否为本平台的资金预算表");
            }
            //将excel数据转成对应的资金预算实力类
            List<CapitalBudget> capitalBudgetList = MapToCapitalBudget.mapToCapitalBudget(list, payTime,platform);

            EntityWrapper<CapitalBudget> wrapper = new EntityWrapper<>();
            wrapper.eq("platform", platform);
            wrapper.eq("rev_date", payTime);

            List<CapitalBudget> capitalBudgets = this.selectList(wrapper);
            if (!capitalBudgets.isEmpty()) {
                throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "当月资金表已经存在，不允许导入");
            }
            //将表数据插入数据库
            this.insertBatch(capitalBudgetList);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }

    /**
     * 描述:下载资金预算表模板
     * 创建人: laoyu
     * 日期: 2018/8/8 0008
     * 时间: 上午 11:44
     */
    @Override
    public Map<String, Object> download() {
        Map<String,Object> downloadMap = new HashMap<>();
        String time = new SimpleDateFormat("yyyy-MM").format(new Date());
        Rate rate = rateService.search(time);
        downloadMap.put("name",ShiroKit.getUser().getDeptcode().toUpperCase()+"资金收支预算表");
        downloadMap.put("platform",ShiroKit.getUser().getDeptcode().toUpperCase());
        downloadMap.put("time",time.replace("-","年")+"月");
        downloadMap.put("rate",rate.getRate());

        return downloadMap;
    }
}
